<!--
 * @Author       : xiaoxiaoguai
 * @Date         : 2025-06-06 09:53:51
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2025-07-31 19:37:54
 * @Description  : 
-->
<!-- 在这个文件对每个tab对应的列表进行渲染 -->
<template>
	<view class="content">
		<!--  :enable-back-to-top="currentIndex===tabIndex" 在微信小程序上可以多加这一句，因为默认是允许点击返回顶部的，但是这个页面有多个scroll-view，会全部返回顶部，所以需要控制是当前index才允许点击返回顶部 -->
		<!-- 如果当前页已经加载过数据或者当前切换到的tab是当前页，才展示当前页数据（懒加载） -->
		<z-paging
			v-if="firstLoaded || isCurrentPage"
			ref="pagingRef"
			v-model="dataList"
			:enable-back-to-top="currentIndex === tabIndex"
			@scroll="scroll"
			@query="queryList"
			:paging-style="{ background: '#f5f5f5', paddingTop: '10rpx' }"
			:show-refresher-when-reload="true"
			:auto-show-back-to-top="true"
			:refresher-fps="0"
			:refresher-end-bounce-enabled="false"
			:refresher-default-duration="0"
			:refresher-complete-delay="150"
			refresher-pulling-text="松开刷新"
			refresher-default-text="再往下拉"
			:refresher-complete-duration="0"
			:refresher-refreshing-scrollable="false"
			:fixed="false"
			:auto-height="false"
			>
			<!-- 自定义返回顶部view -->
			<!-- <template #backToTop>
				<custom-back-to-top ref="backToTop" :current="currentPage" :total="total" />
			</template> -->
			<!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
			<view
				class="order-item"
				v-for="(item, index) in dataList"
				:key="index"
				@tap="detail(item.orderId)">
				<list-cell :hover="false">
					<view class="w-100 d-flex align-items-center">
						<view class="flex-fill d-flex flex-column">
							<view class="font-size-lg text-color-base" style="font-weight: bold;color: #000;font-size: 34rpx;">
								{{ item.shopName }}
							</view>
							<!-- <view class="font-size-sm text-color-assist">
								取餐号：{{ item.numberId }}
							</view> -->
							<!-- <view class="font-size-sm text-color-assist">
								订单编号：{{ item.orderId }}
							</view> -->
						</view>
						<view class="currentStatusColor">
							{{ item.statusDto.title }}
						</view>
					</view>
				</list-cell>
				<list-cell :hover="false" last>
					<view class="w-100 d-flex flex-column">
						<view
							class="w-100 mb-2 text-truncate cartInfoBox font-size-lg text-color-base">
							<scroll-view scroll-x class="cartInfoBoxInner">
								<view
									class="flex cartInfoItem"
									v-for="(good, index) in item.cartInfo"
									:key="index">
									<view class="cartInfoItemInner">
										<image
											:src="good.image"
											mode="aspectFill"
											class="image"></image>
										<view
											class="flex cartInfoItem_rightArea"
											v-if="item.cartInfo.length == 1">
											{{ good.title }}
										</view>
									</view>
								</view>
							</scroll-view>
							<view class="fixedArea">
								<view class="topArea">
									¥
									<text>{{ item.payPrice }}</text>
								</view>
								<view class="bottom">共 {{ goodsNum(item.cartInfo) }} 件</view>
							</view>
						</view>
						<view
							class="d-flex justify-content-between align-items-center"
							style="margin-bottom: 10px">
							<view class="font-size-medium text-color-assist">
								{{ formatDateTime(item.createTime) }}
							</view>
						</view>
						<view class="d-flex align-items-center justify-content-end">
							<view>
								<button
									v-if="
										item.paid > 0 && item.status == 1 && item.refundStatus == 0
									"
									class="left-margin border-radiusClass"
									plain
									size="mini"
									@tap.stop="receive(item)">
									确认收到餐
								</button>
								<button
									v-if="item.status == 3"
									class="left-margin border-radiusClass"
									plain
									size="mini"
									@tap.stop="goComment(item,false)">
									评价
								</button>
								<button
									v-if="item.status == 8"
									class="left-margin border-radiusClass"
									plain
									size="mini"
									@tap.stop="goComment(item,true)">
									查看评价
								</button>
								<button
									class="left-margin border-radiusClass"
									v-if="item.status == 0 && item.paid == 0 && item.isTimeout == 0"
									plain
									size="mini"
									@tap.stop="payMoney(item.orderId)">
									立即支付
								</button>
							</view>
						</view>
					</view>
				</list-cell>
			</view>
		</z-paging>
	</view>
</template>

<script setup>
	import { ref, watch, nextTick, onMounted, computed } from 'vue'
	import { orderGetOrders, orderReceive } from '@/api/order'
	import { formatDateTime, kmUnit } from '@/utils/util'
	// props
	const props = defineProps({
		tabIndex: {
			type: Number,
			default: 0,
		},
		currentIndex: {
			type: Number,
			default: 0,
		},
		currentItem: {
			type: Object,
			default: () => {},
		},
	})

	const goodsNum = computed(() => {
		//计算单个饮品添加到购物车的数量
		return goods => {
			let num = 0
			goods.forEach(good => (num += parseInt(good.number)))
			return num
		}
	})
	//
	const emit = defineEmits(['reloadCurrentListForOrder'])
	const currentPage = ref(0)
	const total = ref(0)
	// 变量
	const backToTop = ref()
	const scroll = () => {
		if (backToTop.value) {
			backToTop.value.isScroll()
		}
	}
	const dataList = ref([])
	const firstLoaded = ref(false)
	const isCurrentPage = ref(false)
	const pagingRef = ref(null)
	const detail = id => {
		uni.navigateTo({
			url: `/pages/components/pages/orders/detail?id=${id}`,
		})
	}
	const payMoney = id => {
	    uni.navigateTo({
			url: `/pages/components/pages/payType/payType?id=${id}&noSaveOrderId=${true}`,
		})
	}
	// 确认收到货
	const receive = async order => {
		let data = await orderReceive({ uni: order.orderId })
		if (data) {
			emit('reloadCurrentListForOrder')
		}
	}
	const goComment = async (order,disabled=false) => {
		uni.navigateTo({
			url: `/pages/components/pages/comment/comment?image=${order.shop.image}&shopName=${order.shop.name}&id=${order.id}&disabled=${disabled}`,
		})
	}
	// 懒加载监听
	watch(
		() => props.currentIndex,
		newVal => {
			if (newVal === props.tabIndex) {
				console.log('滚动到当前页')
				if (!firstLoaded.value) {
					nextTick(() => {
						setTimeout(() => {
							isCurrentPage.value = true
						}, 100)
					})
				}
			}
		},
		{ immediate: true }
	)

	// 刷新列表方法
	const reload = () => {
		nextTick(() => {
			pagingRef.value?.reload()
		})
	}

	// 列表请求函数（z-paging会自动调用）
	const queryList = async (pageNo, pageSize) => {
		currentPage.value = pageNo
		try {
			const ordersData = await orderGetOrders({
				page: pageNo,
				limit: pageSize,
				type: props.currentItem.type,
			})
			setTimeout(() => {
				pagingRef.value?.complete(ordersData.list)
				firstLoaded.value = true
				total.value = ordersData.total
			}, 200)
		} catch (err) {
			pagingRef.value?.complete(false)
		}
	}

	// 点击 item
	const itemClick = item => {
		console.log('点击了', item.title)
	}

	// 暴露方法给父组件调用
	defineExpose({
		reload,
	})
</script>

<style scoped lang="scss">
	/* 注意:父节点需要固定高度，z-paging的height:100%才会生效 */
	.content {
		height: 100%;
	}
	.order-item {
		margin: 0 20rpx;
		margin-bottom: 20rpx;
		background-color: #fff;
		border-radius: 20rpx !important;
		overflow: hidden !important;
	}
	.left-margin {
		margin-left: 10rpx;
	}
	.border-radiusClass{
		border-radius: 200rpx;
		border: 1px solid #dcdcdc;
		color: #000;;
	}
	.image {
		width: 120rpx;
		height: 120rpx;
		background-color: #f6f6f6;
		border-radius: 10rpx;
	}
	.currentStatusColor{
		color:$qingzhen-btn-primary-color;
		color:#666;
	}
	.cartInfoBox {
		display: flex;
		position: relative;
		padding-right: 150rpx;
		.cartInfoBoxInner {
			width: 100%;
			.cartInfoItem {
				display: inline-block;
				.cartInfoItemInner{
					height: 120rpx;
					display: flex;
					width: 100%;
					image{
						margin-right: 20rpx;
					}
				}
				.cartInfoItem_rightArea {
					align-items: center;
					flex: 1;
					font-size: 30rpx;
					color: #000;
				}
			}
		}
		.fixedArea {
			display: flex;
			flex-direction: column;
			align-items: flex-end;
			justify-content: center;
			position: absolute;
			right: 0;
			top: 0;
			width: 150rpx;
			height: 100%;
			.topArea {
				font-size: 22rpx;
				margin-bottom: 10rpx;
				text {
					font-size: 34rpx;
					font-weight: bold;
					margin-left: 4rpx;
				}
			}
			.bottom {
				text-align: center;
				font-size: 24rpx;
			}
		}
	}
</style>
